// 云函数调用
export const Mycloud = (url, obj, method) => {
    const { cloud } = getApp();
    return cloud.function.invoke(url, obj, method);
};

// 字符串转对象
export function strToObj(res) {
    for (let key in res) {
        try {
            res[key] = JSON.parse(res[key]);
        } catch (error) {
            res[key];
        }
    }
    return res;
}

// 隐藏姓名
export function hideName(name) {
    if (!name) {
        return `X***5`;
    }
    let first = name.substr(0, 1);
    let end = name.substr(name.length - 1, name.length);
    return `${first}***${end}`;
}

// 将时间转化为 8.10 这种格式
export function setTime(time) {
    let timer = new Date(parseInt(time));
    return `${timer.getMonth() + 1}.${timer.getDate()}`;
}

// 获取服务器时间
export function getServerTime() {
    return new Promise((res) => {
        my.getServerTime({
            success: (result) => {
                res(result);
            },
        });
    });
}

// 获取随机数
export function Random(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;

}

// 获取用户信息
export const userInfo = () => {
    return new Promise((res, rej) => {
        my.authorize({
            scopes: "scope.userInfo",
            success: (result) => {
                my.getAuthUserInfo({
                    success: (userInfo) => {
                        res(userInfo);
                    },
                });
            },
        });
    });
};

// 判断类型
/**
 *
 * @param {*} obj 传入的类型
 * @param {string}  type 判断是否是该类型
 */
export const toType = (obj, type) => {
    let res = Object.prototype.toString.call(obj);
    if (res == `[object ${type}]`) {
        return true;
    }
    return false;
};

// 是否关注店铺
/**
 *
 * @param {Number} sellerId 店铺所属的卖家ID
 * 返回值 {id: "123456", isFavor: true}
 *
 */
export const isFollowStore = (sellerId) => {
    return new Promise((resolve, reject) => {
        my.tb.checkShopFavoredStatus({
            id: sellerId,
            success: (res) => {
                resolve(res);
            },
            fail: (res) => {
                reject(res);
            },
        });
    });
};

// 关注店铺
export const followStore = (sellerId) => {
    return new Promise((resolve, reject) => {
        my.tb.favorShop({
            id: sellerId,
            success: (res) => {
                resolve(res, "success");
            },
            fail: (res) => {
                reject(res, "fail");
            },
        });
    }).catch((err) => {
        return err;
    });
};

// 判断是否关注店铺 没有的话调用关注接口
/**
 *
 * @param {Number} sellerId 店铺所属的卖家ID
 * @param {object} obj {success:()=>{},fail:()=>{}}
 */
export const followStoreFn = async (sellerId, obj) => {
    let res = await isFollowStore(sellerId);

    console.log(res);

    if (res.isFavor == true || toType(res, "String")) return; // 判断是否已经关注店铺 ， 模拟器 返回的是字符串

    let followState = await followStore(sellerId);

    switch (followState.error) {
        case 11 || 2 || 10:
            obj.fail && obj.fail();
            break;
        default:
            obj.success && obj.success();
            break;
    }

    // {error: 11, errorMessage: "用户拒绝"}
    // {}

    // {error: 11, errorMessage: "用户拒绝", message: "用户拒绝"}
    // {success: true}
};

//  获取图片策略
const getImgInfo = {
    array: (arr, callBack) => {
        let arrTest = [];
        arr.map((v, i) => {
            new Promise((reslove) => {
                my.getImageInfo({
                    src: v,
                    success: (res) => {
                        reslove({ ...res, index: i, path: v });
                    },
                });
            }).then((res) => {
                arrTest.splice(res.index, 0, res);

                if (arrTest.length >= arr.length && callBack) {
                    callBack(arrTest);
                }
            });
        });
    },
};
//  获取图片数据
/**
 *
 * @param {*} arr array type :['xxx.jpg',]
 * @param {string} type options : array
 * @param {function} callBack 回调图片数据 (res) => { log(res) }
 * 
 */
export const imgInfoFn = (arr, type, callBack) => {
    getImgInfo[type](arr, callBack);
};
//  获取系统信息
export const getSystemInfo = () => {
    return my.getSystemInfoSync();
};

// 是否收藏商品
export const isCollectProduct = (product) => {
    return new Promise((resolve) => {

        my.tb.checkGoodsCollectedStatus({
            id: parseInt(product),
            success: (res) => {
                resolve(res)
            }
        });

    })

}

// 收藏商品
export const collectProduct = (product) => {
    return new Promise((resolve, reject) => {
        my.tb.collectGoods({
            id: parseInt(product),
            success: (res) => {
                resolve(res)
            },
            fail: (err) => {
                reject(err)
            }
        })
    })
}

// 收货地址
export const showAddress = () => {
    return new Promise((resolve, reject) => {
        my.authorize({
            scopes: 'scope.addressList',
            success: (res) => {

                my.tb.chooseAddress({
                    addAddress: "show",
                    searchAddress: "show",
                    locateAddress: "show"
                }, (res) => {
                    resolve(res)
                }, (res) => {
                    reject(res)
                })

            },
        });
    })
}

/**
 * 
 * @param {*} ele   {site: [x轴,y轴], width: 100, heihgt: 100}
 * @param {*} target  {site: [x轴,y轴], width: 100, heihgt: 100}
 * 根据 site 的 x 轴 和 y 轴 以及宽度 高度 判断是否有碰撞到 
 */
export const collisionDetection = (ele, target) => {
    let eleX = ele.site[0];
    let eleY = ele.site[1];
    let targetX = target.site[0];
    let targetY = target.site[1];

    if (
        eleX + ele.width >= targetX && eleY + ele.height >= targetY &&
        eleX <= targetX + target.width && eleY <= targetY + target.height
    ) {
        return true
    } else {
        return false
    }


}

// 获取本地数据
export const getStorage = (key) => {
    return new Promise((resolve, rej) => {
        my.getStorage({
            key: key,
            success: async (res) => {
                resolve(res)
            }
        });
    })
}

// 设置本地数据
export const setStorage = (key, data) => {
    return new Promise((resolve, reject) => {
        my.setStorage({
            key: key,
            data,
            success: (result) => {
                resolve({ ...result, message: '设置成功' })
            }
        });
    })
}

// 删除本地
export const removeStorage = (key) => {
    return new Promise((resolve, reject) => {
        my.removeStorage({
            key: key,
            success: (result) => {
                resolve({ ...result, message: '删除成功' })
            }
        });
    })

}